import request from '@/axios'
import type { UserType } from './types'

interface RoleParams {
  roleName: string
}

export const loginApi = (data: UserType): Promise<IResponse<UserType>> => {
  data.grant_type = 'password'
  return request.post({
    url: '/app/oauth/token',
    data,
    transformRequest: [
      function (data) {
        // Do whatever you want to transform the data
        let ret = ''
        for (const it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }
    ],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export const refreshApi = (data: UserType): Promise<IResponse<UserType>> => {
  data.grant_type = 'refresh_token'
  return request.post({
    url: '/app/oauth/token',
    data,
    transformRequest: [
      function (data) {
        // Do whatever you want to transform the data
        let ret = ''
        for (const it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret
      }
    ],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
}

export const loginOutApi = (): Promise<IResponse> => {
  // return request.get({ url: '/mock/user/loginOut' })
  return new Promise((resolve) => {
    resolve({
      code: 200,
      data: {}
    })
  })
}

export const getUserApi = (data: object) => {
  return request.get({ url: '/app/appDrivers/page', params: data })
}

export const getUserListApi = ({ params }: AxiosConfig) => {
  return request.get<{
    code: string
    data: {
      list: UserType[]
      total: number
    }
  }>({ url: '/mock/user/list', params })
}

export const getAdminRoleApi = (
  params: RoleParams
): Promise<IResponse<AppCustomRouteRecordRaw[]>> => {
  return request.get({ url: '/mock/role/list', params })
}

export const getTestRoleApi = (params: RoleParams): Promise<IResponse<string[]>> => {
  return request.get({ url: '/mock/role/list2', params })
}
